package com.ylr.自定义枚举类校验;

import org.apache.commons.lang3.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * @Classname EnumValidator
 * @Description TODO
 * @Date 2021/8/13 16:20
 * @Created by ylr
 */
public class EnumValidator implements ConstraintValidator<EnumValueValidation,Object> {


    private Class<? extends Enum>  enumClass ;
    private Boolean isList = false;
    private String methodStr;
    @Override
    public void initialize(EnumValueValidation constraintAnnotation) {
        enumClass  = constraintAnnotation.enumClass();
        isList = constraintAnnotation.isList();
        methodStr = constraintAnnotation.enumMethod();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {

        if (ObjectUtils.isEmpty(value)) return false;

        if (isList){
            List<String> strings = (List<String>) value;
            for (String string : strings) {
                if (!extracted(string) )return false;
            }
            return true;
        }else {
            if (extracted(value)) return true;
        }
        return false;
    }

    private boolean extracted(Object value) {
        try {
            // 反射获取校验需要调用的枚举的方法
            Method method = enumClass.getMethod("name");  //public static Boolean isValid
            // 获取所有的枚举值
            Enum[] enums = enumClass.getEnumConstants();
            // 对每一个枚举值调用 校验的方法，获取返回值，和入参作比较
            for (Enum e : enums) {
                Object returnValue = method.invoke(e,null);
                if (value.toString().equalsIgnoreCase(returnValue.toString())) return true;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            // 异常处理
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            // 异常处理
        }
        return false;
    }
}
